// pages/checkInDetail/index.js
const getCurrentDate = require('../../utils/util').getCurrentDate
const baseUrl = require('../../config').baseUrl
const app = getApp()
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
}
class examineData {
    /*
        检查情况输入的数据
    */
    constructor(value = '') {
        this.value = value
        this.standardimgids = ''
    }
}

class abarbeitungData {
    /*
        整改输入的数据
    */
    constructor(value = '', cursor = 0) {
        this.cursor = cursor
        this.value = value
    }
}

class standardData {
    /*
        隐患排查标准
    */
    constructor() {
        this.typeNav = []
        this.typeChildNav = ''
        this.selectIndex = 0
        this.HideTypeArr = [] // 隐患类别数组
        this.selectHideTypeId = '' // 选中的隐患隐患类别ID
        this.hideStandardArr = []   // 隐患标准数组
        this.currentHideStandardArr = []
        this.selecthideStandardIdArr = []
    }
}

Page({

    /**
     * 页面的初始数据
     */
    data: {
        updateImgList: [],
        examineData: new examineData(),
        abarbeitungData: new abarbeitungData(),
        showPickerType: true, // 显示隐患类别选择弹层
        showPickerCriterion: true, // 显示隐患标准排查弹层
        hasRisk: false, // 是否存在隐患
        standardData: new standardData(),
        animation: null, // 隐患排查标准选择弹出层动画
        date: '', // 整改结束时间
        hideType: '', // 隐患排查
        standardImgList: [],
        companyId: '', //  单位id
        HideTypeArr: [],
        currentDate: getCurrentDate()
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.animation = wx.createAnimation()
        this.selectorQuery = wx.createSelectorQuery()
        this.setData({
            companyId: options.companyId
        })
        this.getHideType()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    /**
     * 获取隐患类别
     */
    getHideType () {
        let This = this
        wx.request({
            url: baseUrl,
            header: {
                "content-type": "application/x-www-form-urlencoded"
            },
            data: {
                data: JSON.stringify({
                    business: "GetHtStandard",
                    data: ''
                })
            },
            method: 'POST',
            success (res) {
                if (res.data.code === 0) {
                    This.setData({
                        'standardData.HideTypeArr': res.data.data,
                        'HideTypeArr': res.data.data
                    })
                } else {
                    wx.showToast({
                        title: res.data.info,
                        icon: 'none',
                        duration: 1000
                    })
                }
            },
            fail: (error) => {
                wx.showToast({
                    title: error.data.info,
                    icon: 'none',
                    duration: 1000
                })
            }
        })
    },
    /**
     * 从本地相册选择图片或使用相机拍照。参数
     */
    chooseImage () {
        let that = this
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success (res) {
                // tempFilePath可以作为img标签的src属性显示图片
                let imgUrl = res.tempFilePaths[0]
                wx.uploadFile({
                    url: baseUrl,
                    filePath: res.tempFilePaths[0],
                    name: 'file',
                    header: {
                        "content-type": "application/x-www-form-urlencoded"
                    },
                    formData: {
                        data: JSON.stringify({
                            business: "WxUploadFile",
                            data: app.globalData.account
                        })
                    },
                    success (res) {
                        res.data = JSON.parse(res.data)
                        if (res.data.code === 0) {
                            that.setData({
                                "updateImgList": that.data.updateImgList.concat({ imgUrl: imgUrl, fileid: res.data.fileid })
                            })
                        }
                    }
                })
            }
        })
    },
    /**
     * 删除上传的图片
     */
    deleteImg (e) {
        let This = this
        wx.request({
            url: baseUrl,
            header: {
                "content-type": "application/x-www-form-urlencoded"
            },
            data: {
                data: JSON.stringify({
                    business: "DeleteWxFile",
                    data: e.currentTarget.dataset.id
                })
            },
            method: 'POST',
            success (res) {
                if (res.data.code === 0) {
                    This.data.updateImgList.splice(e.currentTarget.dataset.index, 1)
                    This.setData({
                        "updateImgList": This.data.updateImgList
                    })
                } else {
                    wx.showToast({
                        title: res.data.info,
                        icon: 'none',
                        duration: 1000
                    })
                }
            },
            fail: (error) => {
                wx.showToast({
                    title: error.data.info,
                    icon: 'none',
                    duration: 1000
                })
            }
        })
    },
    /**
     *  检查情况输入
     */
    inputTextarea (e) {
        let dataName = e.target.dataset.name
        let value = `${dataName}.value`
        if (e.detail.value.length > 100) {
            this.setData({
                [value]: e.detail.value.substr(0, 100)
            })
        } else {
            this.setData({
                [value]: e.detail.value
            })
        }
    },
    /**
     *  显示选择隐患排查的弹层
     */
    showSelectPicker (e) {
        let pickerName = e.currentTarget.dataset.name // 弹出那个弹层
        if (this.data[pickerName]) {
            this.setData({
                [pickerName]: !this.data[pickerName]
            }, () => {
                if (this.moveH) {
                    this.animation.translateY(0).step({
                        duration: 200
                    })
                    this.setData({ animation: this.animation.export() }, () => {
                        setTimeout(() => {
                            this.animation.translateY(-this.moveH).step({
                                duration: 200
                            })
                            this.setData({ animation: this.animation.export() })
                        }, 200)
                    })
                } else {
                    let className = pickerName == 'showPickerType' ? '.picker-content0' : '.picker-content1'
                    this.selectorQuery.select(className).boundingClientRect((rect) => {
                        this.moveH = rect.height
                        this.animation.translateY(-this.moveH).step({
                            duration: 200
                        })
                        this.setData({ animation: this.animation.export() })
                    }).exec()
                }
            })
        } else {
            this.animation.translateY(0).step({
                duration: 200
            })
            this.setData({ animation: this.animation.export() }, () => {
                setTimeout(() => {
                    this.setData({
                        [pickerName]: !this.data[pickerName]
                    })
                }, 200)
            })
        }
    },
    /**
     *  切换是否有风险
     */
    changeHasRisk (e) {
        this.setData({
            "hasRisk": e.currentTarget.dataset.value
        })
    },
    /**
     * 选择隐患类别
     */
    selectHideType (e) {
        wx.showToast({
            title: '数据加载中',
            icon: 'none',
            duration: 1000
        })
        this.animation.translateY(0).step({
            duration: 200
        })
        this.setData({ animation: this.animation.export() }, () => {
            setTimeout(() => {
                if (this.data.standardData.selectHideTypeId == e.currentTarget.dataset.id) {
                    return false
                }
                this.setData({
                    "hideType": e.currentTarget.dataset.name,
                    "showPickerType": true,
                    "standardData.selectHideTypeId": e.currentTarget.dataset.id,
                    "standardData.typeNav": [],
                    "standardData.selecthideStandardIdArr": [],
                    "standardData.selectIndex": 0,
                    "standardData.currentHideStandardArr": [],
                    "examineData.value": '',
                    "abarbeitungData.value": ''
                })
                let This = this
                wx.request({
                    url: baseUrl,
                    header: {
                        "content-type": "application/x-www-form-urlencoded"
                    },
                    data: {
                        data: JSON.stringify({
                            business: "GetHtStandard",
                            data: this.data.standardData.selectHideTypeId
                        })
                    },
                    method: 'POST',
                    success (res) {
                        if (res.data.code === 0) {
                            This.setData({
                                'standardData.hideStandardArr': res.data.data,
                                'standardData.currentHideStandardArr': res.data.data
                            })
                        } else {
                            wx.showToast({
                                title: res.data.info,
                                icon: 'none',
                                duration: 1000
                            })
                        }
                    },
                    fail: (error) => {
                        wx.showToast({
                            title: error.data.info,
                            icon: 'none',
                            duration: 1000
                        })
                    },
                    complete: () => {
                        wx.hideLoading()
                    }
                })
            }, 200)
        })
    },
    /**
     * 选择隐患排查标准
     */
    selectHideStandard (e) {
        if (!this.disbaleClick) {
            this.disbaleClick = true
            let selecthideStandardIdArr = this.data.standardData.selecthideStandardIdArr // 选中的隐患标准数组
            let selectIndex = this.data.standardData.selectIndex // 当前选择的隐患标准 nav 的index
            let currentHideStandardArr = this.data.standardData.currentHideStandardArr
            if (!selecthideStandardIdArr[this.data.standardData.selectIndex] || e.currentTarget.dataset.item) {
                selecthideStandardIdArr[this.data.standardData.selectIndex] = []
            }
            if (selecthideStandardIdArr[this.data.standardData.selectIndex].join(",").indexOf(e.currentTarget.dataset.id) != -1 && e.currentTarget.dataset.item) {
                return false
            } else if (selecthideStandardIdArr[this.data.standardData.selectIndex].join(",").indexOf(e.currentTarget.dataset.id) != -1 && !e.currentTarget.dataset.item) {
                selecthideStandardIdArr[selectIndex].remove(e.currentTarget.dataset.id)
                for (let i = 0; i < currentHideStandardArr.length; i++) {
                    if (currentHideStandardArr[i].id == e.currentTarget.dataset.id) {
                        currentHideStandardArr[i].selected = false
                        this.setData({
                            "standardData.selecthideStandardIdArr": selecthideStandardIdArr,
                            "standardData.currentHideStandardArr": currentHideStandardArr
                        }, () => {
                            this.disbaleClick = false
                        })
                        return false
                    }
                }
            }
            selecthideStandardIdArr[this.data.standardData.selectIndex].push(e.currentTarget.dataset.id)
            currentHideStandardArr.forEach((item, index) => {
                if (selecthideStandardIdArr[this.data.standardData.selectIndex].join(',').indexOf(item.id) != -1) {
                    this.setData({
                        [`standardData.currentHideStandardArr[${index}].selected`]: true
                    }, () => {
                        this.disbaleClick = false
                    })
                } else {
                    this.setData({
                        [`standardData.currentHideStandardArr[${index}].selected`]: false
                    }, () => {
                        this.disbaleClick = false
                    })
                }
            })
            if (e.currentTarget.dataset.item) {
                let typeNav = this.data.standardData.typeNav
                typeNav.splice(selectIndex, 1, {
                    name: e.currentTarget.dataset.name,
                    id: e.currentTarget.dataset.id
                })
                selectIndex++
                selecthideStandardIdArr[selectIndex] = []
                this.setData({
                    "standardData.typeNav": typeNav,
                    "standardData.selecthideStandardIdArr": selecthideStandardIdArr,
                    "standardData.currentHideStandardArr": e.currentTarget.dataset.item,
                    "standardData.selectIndex": selectIndex
                }, () => {
                    this.disbaleClick = false
                })
            }
        }
    },
    /**
     * 隐患标准排查nav切换
     */
    changeNavIndex (e) {
        this.setData({
            "standardData.selectIndex": e.currentTarget.dataset.navindex
        })
        this.changeCurrentHideStandardArr(e.currentTarget.dataset.id)
    },
    /**
     * 切换当前隐患标准的数组
     */
    changeCurrentHideStandardArr (id, arr) {
        let hideStandardArr = arr ? arr : this.data.standardData.hideStandardArr
        for (let i = 0; i < hideStandardArr.length; i++) {
            if (hideStandardArr[i].id == id) {
                this.setData({
                    "standardData.currentHideStandardArr": hideStandardArr,
                })
                return false
            } else if (hideStandardArr[i].children) {
                this.changeCurrentHideStandardArr(id, hideStandardArr[i].children)
            }
        }
    },
    /**
     * 预览隐患排查标准图片
     */
    previewImage (e) {
        var current = e.target.dataset.src;
        wx.previewImage({
            current: current, // 当前显示图片的http链接  
            urls: this.data.standardImgList // 需要预览的图片http链接列表  
        })
    },
    /**
    * 预览整改前图片
    */
    previewBeforeZGImage (e) {
        var current = e.target.dataset.src;
        let urls = []
        this.data.updateImgList.forEach(item => {
            urls.push(item.imgUrl)
        })
        wx.previewImage({
            current: current, // 当前显示图片的http链接  
            urls: urls // 需要预览的图片http链接列表  
        })
    },
    /**
     * 选择时间
     */
    bindDateChange (e) {
        this.setData({
            date: e.detail.value
        })
    },
    /**
     * 确认选择的隐患排查标准
     */
    affirmHideStandar (e) {
        let currentHideStandardArr = this.data.standardData.currentHideStandardArr
        let hideDescribe = ''
        let hideZG = ''
        let hideDescribeIds = ''
        let standardImgList = []
        currentHideStandardArr.forEach(item => {
            if (item.selected) {
                hideDescribe += item.name
                hideZG = item.measure ? hideZG + item.measure : hideZG
                standardImgList = standardImgList.concat(item.file)
                if (hideDescribeIds) {
                    hideDescribeIds += `,${item.id}`
                } else {
                    hideDescribeIds += item.id
                }
            }
        })
        this.animation.translateY(0).step({
            duration: 200
        })
        this.setData({ animation: this.animation.export() }, () => {
            this.setData({
                'examineData.value': hideDescribe,
                'examineData.standardimgids': hideDescribeIds,
                'standardImgList': standardImgList,
                'abarbeitungData.value': hideZG,
                showPickerCriterion: true
            })
        })
    },

    /**
     * 完成隐患登记
     */
    submitHideLogin () {
        let This = this
        let problemimgs = ''
        this.data.updateImgList.forEach(item => {
            if (problemimgs) {
                problemimgs += `,${item.fileid}`
            } else {
                problemimgs += `${item.fileid}`
            }
        })

        let toastText = '' // 提示语
        if (this.data.hideType === '') {
            toastText = '请选择隐患类别'
        } else if (this.data.examineData.value === '') {
            toastText = '请选择或输入隐患描述'
        } else if (problemimgs === '') {
            toastText = '请上传整改前图片'
        } else if (this.data.abarbeitungData.value === '') {
            toastText = '请输入整改措施'
        } else if (this.data.date === '') {
            toastText = '请选择整改完成时间'
        }
        if (toastText) {
            wx.showToast({
                title: toastText,
                icon: 'none',
                duration: 2000
            })
            return false
        }
        wx.request({
            url: baseUrl,
            header: {
                "content-type": "application/x-www-form-urlencoded"
            },
            data: {
                data: JSON.stringify({
                    business: "SaveHiddenDanger",
                    data: {
                        account: app.globalData.account,
                        deptid: this.data.companyId,
                        category: this.data.hideType,
                        categoryid: this.data.standardData.selectHideTypeId,
                        description: this.data.examineData.value,
                        hdlevel: this.data.hasRisk ? '重大隐患' : '一般隐患',
                        measure: this.data.abarbeitungData.value,
                        resolveendtime: this.data.date,
                        problemimgs: problemimgs,
                        standardimgids: this.data.examineData.standardimgids
                    }
                })
            },
            method: 'POST',
            success (res) {
                if (res.data.code === 0) {
                    wx.showToast({
                        title: '登记成功',
                        icon: 'none',
                        duration: 2000
                    })
                    This.setData({
                        updateImgList: [],
                        examineData: new examineData(),
                        abarbeitungData: new abarbeitungData(),
                        showPickerType: true, // 显示隐患类别选择弹层
                        showPickerCriterion: true, // 显示隐患标准排查弹层
                        hasRisk: false, // 是否存在隐患
                        standardData: new standardData(),
                        animation: null, // 隐患排查标准选择弹出层动画
                        date: '', // 整改结束时间
                        hideType: '', // 隐患排查
                        standardImgList: [],
                        'standardData.HideTypeArr': This.data.HideTypeArr
                    })
                } else {
                    wx.showToast({
                        title: res.data.info,
                        icon: 'none',
                        duration: 2000
                    })
                }
            },
            fail: (error) => {
                wx.showToast({
                    title: error.data.info,
                    icon: 'none',
                    duration: 1000
                })
            }
        })
    }
})